package cn.test.future.cf;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;

@Slf4j
public class CompletableFutureTest2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (new Random().nextInt(10) % 2 == 0) {
                int i = 12 / 0;
            }

            log.debug("执行结束");

            return "阿萨撒所多";
        });

        future.whenComplete(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String s, Throwable throwable) {
                log.debug(s + "， 执行完毕");
            }
        });

        future.exceptionally(new Function<Throwable, String>() {
            @Override
            public String apply(Throwable throwable) {
                log.debug("执行失败：" + throwable.getMessage());
                return "异常XXXX";
            }
        });

        // join放在这里，正常运行情况，whenComplete不生效，可以放在whenComplete后面链式调用解决，也可以在这句代码之前sleep几秒解决，真奇怪，我试图从源码寻找答案，但我仅仅看了一眼，我就G了
        future.join();
    }
}
